/**
 * MIT License
 *
 * Copyright (c) 2024 小村程序员
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.core.instrument;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AnalyzerAdapter;
import org.open.cobertura.core.provider.CoberturaClassFieldProbeArrayProvider;
import org.open.cobertura.core.provider.CoberturaProbeIndexProvider;

/**
 * 用于对类进行探针插桩
 *
 */
public class CoberturaClassProbeAdapter extends ClassVisitor implements CoberturaProbeIndexProvider {
    /**
     * 索引计数器
     */
    private int index;
    private CoberturaClassProbeVisitor ccpv;
    private long classId;
    private String className;
    private boolean isInterface;
    public CoberturaClassProbeAdapter(final int asm,final CoberturaClassProbeVisitor ccpv,final long classId) {
        super(asm,ccpv);
        this.ccpv = ccpv;
        this.classId=classId;
    }


    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces);
        this.className=name;
        if ((access & Opcodes.ACC_INTERFACE) != 0) {
            isInterface = true;
        }
    }

    /**
     * 访问方法
     * CoberturaMethodNodeAdapater 方法AST抽象语法树适配器
     *          |__CoberturaMethodProbeAdapter 方法非AST语法树适配器，由CoberturaMethodNodeAdapater转换而来
     *                   |__CoberturaMethodProbeVisitor 抽象方法访问器 -->CoberturaMethodInsrumenter 具体的插桩链
     * @param access the method's access flags (see {@link Opcodes}). This parameter also indicates if
     *     the method is synthetic and/or deprecated.
     * @param name the method's name.
     * @param descriptor the method's descriptor (see {@link Type}).
     * @param signature the method's signature. May be {@literal null} if the method parameters,
     *     return type and exceptions do not use generic types.
     * @param exceptions the internal names of the method's exception classes (see {@link
     *     Type#getInternalName()}). May be {@literal null}.
     * @return
     */
    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions){
        if(isInterface){
            final MethodVisitor mv= cv.visitMethod(access,name,descriptor,signature,exceptions);
            return mv;
        }

        final CoberturaClassProbeAdapter indexProvide=this;
        final CoberturaMethodProbeVisitor mv2=ccpv.visitMethod(access,name,descriptor,signature,exceptions,classId);
        final String className=this.className;
        final String methodName=name;
        return new CoberturaMethodNodeAdapater(Opcodes.ASM9,access,name,descriptor,signature,exceptions){
            @Override
            public void visitEnd() {
                super.visitEnd();
                final MethodVisitor labelFlowerInfo=new CoberturaLabelStatefulVisitor();
                this.instructions.accept(labelFlowerInfo);
                final CoberturaMethodProbeAdapter mv3=new CoberturaMethodProbeAdapter(Opcodes.ASM9,mv2,methodName,classId,className,indexProvide);
                mv3.visitMethodInsn(Opcodes.INVOKESTATIC, className, "__cobertura_counter", "()V", false);
                final AnalyzerAdapter analyzer = new AnalyzerAdapter(CoberturaClassProbeAdapter.this.className, access, name, desc, mv3);
                mv3.setAnalyzerAdapter(analyzer);
                mv2.accept(this,mv3);

            }
        };
    }

    /**
     * 这里给类插入全局字段
     */
    @Override
    public void visitEnd() {
        if(isInterface){
            super.visitEnd();
            return;
        }
        CoberturaClassFieldProbeArrayProvider classFieldProbeArrayFactory=new CoberturaClassFieldProbeArrayProvider(ccpv);
        classFieldProbeArrayFactory.addProbeMemberVar(this.classId,this.className, index);
        super.visitEnd();
    }

    /**
     * 索引自增方法
     * @return
     */
    public int indexIncrement(){
        return index++;
    }
}
